package com.bw.home.adapter

import android.animation.ObjectAnimator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ViewAnimator
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.bw.cache.cache.RecyclerCachePool
import com.bw.common.entity.SimpleVideoEntity
import com.bw.home.R
import com.bw.home.cache.HomeItemCache
import com.bw.home.databinding.ItemVideoLayoutBinding
import com.bw.image.glide.GlideImgLoader
import kotlin.math.max

class HomeVideoListAdapter constructor(private val list: MutableList<SimpleVideoEntity>): RecyclerView.Adapter<HomeVideoListAdapter.ItemViewHolder>() {

    private var scrollState = RecyclerView.SCROLL_STATE_IDLE //滚动停止
    var preloadEndCount = 0 //倒数第几个触发预加载
    private var currentPlayerPosition = -1 // 当前正在播放的视频位置
    private var isPreloading = false //是否在预加载中
    var preloadMoreData: (()->Unit)? = null //回调方法

    var itemViewCache: HomeItemCache?= null
    private var itemClickListener: OnItemClickListener ?= null
    fun setOnItemClickListener(l: OnItemClickListener){
        itemClickListener = l
    }

    inner class ItemViewHolder(val dataBinding: ItemVideoLayoutBinding): RecyclerView.ViewHolder(dataBinding.root)

    //点击事件接口
    interface OnItemClickListener{
        fun onItemChick(v: View, position: Int)
    }

    override fun getItemCount(): Int = list.size

    override fun getItemViewType(position: Int): Int {
        return RecyclerCachePool.HOME_LIST_ITEM_VIEW_TYPE
    }

    override fun getItemId(position: Int): Long = position.toLong()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val itemViewHolder = ItemViewHolder(ItemVideoLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false))
        itemViewCache?.addViewHolder(viewType, itemViewHolder)
        return itemViewHolder
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {


        val entity = list[position]
        //视频标题和描述
        holder.dataBinding.tvTitle.text = entity.title
        holder.dataBinding.tvRun.text = entity.description

        holder.dataBinding.tvAuthname.text = entity.name
        //仿抖音滑动

        //用户头像 圆角
        GlideImgLoader.loadCircleImage(holder.dataBinding.root.context, entity.avatar_url, holder.dataBinding.ivUserIcon)
        GlideImgLoader.loadCircleImage(holder.dataBinding.root.context, entity.avatar_url, holder.dataBinding.ivRotation)
       // GlideImgLoader.loadBoundImage(holder.dataBinding.root.context, entity.image_url,10, holder.dataBinding.ivUserIcon)

        val ivRotation = holder.dataBinding.ivRotation
        val rotaton = ObjectAnimator.ofFloat(ivRotation, "rotation", 0f, 360f)
        rotaton.duration = 1000
        rotaton.repeatCount=ViewAnimator.INVISIBLE
        rotaton.start()


        //播放按钮点击事件
        holder.dataBinding.gsy.apply {
            setUp(entity.videopath,true,"")
            backButton.visibility=View.GONE
            startPlayLogic()
        }

        //评论按钮点击事件
        holder.dataBinding.ivComment.setOnClickListener {
            itemClickListener?.onItemChick(it, position)
        }

        //更多按钮点击事件
        holder.dataBinding.ivShare.setOnClickListener {
            itemClickListener?.onItemChick(it, position)
        }
        // 根据位置控制播放
        checkPreloadMoreData(position)

    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        if (itemViewCache != null){
            recyclerView.setViewCacheExtension(itemViewCache)
        }
        //添加滚动监听事件
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                scrollState = newState
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        itemViewCache?.clearCache()
    }

    /**
     * 数据预加载
     */
    private fun checkPreloadMoreData(position: Int){
        if (scrollState != RecyclerView.SCROLL_STATE_IDLE //滚动中触发
            && position == max(list.size - 1 - preloadEndCount, 0) //当前页面最后第preloadEndCount个触发
            && !isPreloading){
            //正在触发加载标识
            isPreloading = true
            //执行回调方法
            preloadMoreData?.invoke()
        } else {
            isPreloading = false
        }
    }
    fun playVideoAtPosition(position: Int) {
        // 停止当前播放的视频
        if (currentPlayerPosition >= 0) {
            notifyItemChanged(currentPlayerPosition)
        }

        // 播放新视频
        currentPlayerPosition = position
        notifyItemChanged(position)
    }






}